﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Qcy.Jshj.Web.Models;

namespace Qcy.Jshj.Web.Controllers
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/
        JshjDataContext context = new JshjDataContext();

        public ActionResult Index()
        {
            return View();
        }

        #region  /*(-_-)*/分类操作/*(-_-)*/

        public ActionResult ProductCategories()
        {
            return View();
        }

        public JsonResult GetProductCatgories()
        {
            var source = context.ProductCategory.Include("Parent");
            var parent = from q in source
                         where q.Parent == null
                         select new Category
                         {
                             id = q.Id,
                             name = q.Name,
                             nameEn = q.NameEn,
                             description = q.Description,
                             descriptionEn = q.DescriptionEn
                         };
            var tree = new List<Category>();
            foreach (var item in parent)
            {
                item.children = from q in source
                                where q.Parent.Id == item.id
                                select new Category()
                                {
                                    id = q.Id,
                                    name = q.Name,
                                    nameEn = q.NameEn,
                                    description = q.Description,
                                    descriptionEn = q.DescriptionEn
                                };
                tree.Add(item);
            }

            return Json(tree);
        }

        public JsonResult Category(Category category)
        {
            ProductCategory c;
            if (category.id == 0)
            {
                c = new ProductCategory();
                if (category.pid > 0)
                    c.Parent = context.ProductCategory.FirstOrDefault(s => s.Id == category.pid);
                context.ProductCategory.Add(c);
            }
            else
            {
                c = context.ProductCategory.Include("Parent").First(cc => cc.Id == category.id);
            }
            UpdateModel(c);
            c.Name = category.name;
            c.NameEn = category.nameEn;
            c.Description = category.description;
            c.DescriptionEn = category.descriptionEn;
            context.SaveChanges();

            return Json(new { result = true, msg = "更新成功" }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DeleteCategory(int id)
        {
            var category = context.ProductCategory.FirstOrDefault(c => c.Id == id);
            var ccount = context.ProductCategory.Include("Parent").Count(s => s.Parent.Id == id);
            if (ccount > 0)
                return Json(new { result = 0, msg = string.Format("分类\"{0}\"下有{1}个子分类,不得删除!", category.Name, ccount) });
            var count = 0;//context.Product.Include(s => s.Category).Count(s => s.Category.Id == id);
            if (count <= 0)
            {
                context.ProductCategory.Remove(category);
                context.SaveChanges();
                return Json(new { result = 0, msg = "删除成功" });
            }
            return Json(new { result = 0, msg = string.Format("分类\"{0}\"下有{1}个案例,不得删除!", category.Name, count) });
        }
        #endregion

        #region  /*(-_-)*/产品操作/*(-_-)*/

        public ActionResult Products()
        {
            return View();
        }

        public JsonResult GetProduct(int Id)
        {
            return Json(context.Product.Include("Category").FirstOrDefault(c => c.Id == Id), JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetProducts(int page, int rows, string keyword, DateTime? datestart, DateTime? dateend)
        {
            IQueryable<Product> source = context.Product.Include("Category");
            if (!string.IsNullOrEmpty(keyword))
            {
                source = source.Where(c => c.Title.Contains(keyword) || c.Category.Name.Contains(keyword));
            }
            if (datestart.HasValue)
                source = source.Where(s => s.CreationDate >= datestart.Value);
            if (dateend.HasValue)
                source = source.Where(s => s.CreationDate <= dateend.Value.AddDays(1));
            var result = source.OrderByDescending(c => c.Id).Skip(rows * (page - 1)).Take(rows);
            return Json(new { total = source.Count(), rows = result }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult Product(int Id, int CategoryId)
        {
            Product p;
            if (Id == 0)
            {
                p = new Product();
                context.Product.Add(p);
            }
            else
            {
                p = context.Product.FirstOrDefault(s => s.Id == Id);
            }
            UpdateModel(p);
            p.CreationDate = DateTime.Now;
            p.Category = context.ProductCategory.FirstOrDefault(s => s.Id == CategoryId);

            if (!string.IsNullOrEmpty(p.Pictures) && p.Pictures.StartsWith(","))
                p.Pictures = p.Pictures.TrimStart(',');

            context.SaveChanges();

            return Json(new { result = true, msg = "更新成功" }, "text/html");
        }

        [HttpPost]
        public JsonResult DeleteProduct(int id)
        {
            context.Product.Remove(context.Product.FirstOrDefault(c => c.Id == id));
            context.SaveChanges();
            return Json(new { result = true, msg = "删除产品成功" }, "text/html");
        }

        #endregion

        #region  /*(-_-)*/质量控制/*(-_-)*/

        public ActionResult Quanlities()
        {
            ViewBag.Title = "质量控制";
            var model = context.CompanyInfo.Where(s => s.InfoType == CompanyInfoType.Quality).ToList();
            return View("CompanyInfos", model);
        }

        #endregion

        #region  /*(-_-)*/关于我们/*(-_-)*/
        public ActionResult CompanyInfos()
        {
            ViewBag.Title = "关于我们";
            var model = context.CompanyInfo.Where(s => s.InfoType == CompanyInfoType.About && s.Id != 1).ToList();
            return View("CompanyInfos", model);
        }

        public JsonResult GetCompanyInfo(int id)
        {
            return Json(context.CompanyInfo.FirstOrDefault(c => c.Id == id), JsonRequestBehavior.AllowGet);
        }


        [HttpPost, ValidateInput(false)]
        public JsonResult CompanyInfo(int Id)
        {
            CompanyInfo c;
            if (Id == 0)
            {
                c = new CompanyInfo();
                context.CompanyInfo.Add(c);
            }
            else
            {
                c = context.CompanyInfo.First(cc => cc.Id == Id);
            }
            UpdateModel(c);
            context.SaveChanges();

            var result = new { result = "提交成功", id = Id, content = c.Content };
            return Json(result, "text/html");
        }
        #endregion

        #region  /*(-_-)*/服务支持/*(-_-)*/
        public ActionResult Services()
        {
            ViewBag.Title = "服务支持";
            var model = context.CompanyInfo.Where(s => s.InfoType == CompanyInfoType.Service).ToList();
            return View("CompanyInfos", model);
        }
        #endregion

        #region  /*(-_-)*/联系订购/*(-_-)*/
        public ActionResult ContactNOrders()
        {
            ViewBag.Title = "联系订购";
            var model = context.CompanyInfo.Where(s => s.InfoType == CompanyInfoType.Order && s.MenuShow).ToList();
            return View("CompanyInfos", model);
        }
        #endregion

        #region  /*(-_-)*/公司动态/*(-_-)*/

        public ActionResult Articles()
        {
            return View();
        }

        public JsonResult GetArticles(int page, int rows, string keyword, DateTime? datestart, DateTime? dateend)
        {
            IQueryable<Article> source = context.Article;
            if (!string.IsNullOrEmpty(keyword))
            {
                source = source.Where(c => c.Title.Contains(keyword));
            }
            if (datestart.HasValue)
                source = source.Where(s => s.CreationDate >= datestart.Value);
            if (dateend.HasValue)
                source = source.Where(s => s.CreationDate <= dateend.Value.AddDays(1));
            var result = source.OrderByDescending(c => c.Id).Skip(rows * (page - 1)).Take(rows);
            return Json(new { total = source.Count(), rows = result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetArticle(int Id)
        {
            return Json(context.Article.FirstOrDefault(c => c.Id == Id), JsonRequestBehavior.AllowGet);
        }


        [HttpPost, ValidateInput(false)]
        public ActionResult Article(int Id = 0)
        {
            Article c;
            if (Id == 0)
            {
                c = new Models.Article();
                context.Article.Add(c);
            }
            else
            {
                c = context.Article.First(cc => cc.Id == Id);
            }
            UpdateModel(c);
            c.CreationDate = DateTime.Now;
            context.SaveChanges();
            var result = new { result = "提交成功" };
            return Json(result, "text/html");
        }

        [HttpPost]
        public JsonResult DeleteArticle(int id)
        {
            context.Article.Remove(context.Article.FirstOrDefault(c => c.Id == id));
            context.SaveChanges();
            return Json(new { result = true, msg = "删除资讯成功" }, "text/html");
        }
        #endregion

        #region  /*(-_-)*/在线订单/*(-_-)*/
        public ActionResult Orders()
        {
            return View();
        }

        public ActionResult GetOrders(int page, int rows, string keyword, DateTime? datestart, DateTime? dateend)
        {

            IQueryable<Order> source = context.Order;
            if (!string.IsNullOrEmpty(keyword))
            {
                source = source.Where(c => c.LinkMan.Contains(keyword) || c.Phone.Contains(keyword) || c.Email.Contains(keyword));
            }
            if (datestart.HasValue)
                source = source.Where(s => s.CreationDate >= datestart.Value);
            if (dateend.HasValue)
                source = source.Where(s => s.CreationDate <= dateend.Value.AddDays(1));
            var result = source.OrderByDescending(c => c.Id).Skip(rows * (page - 1)).Take(rows);
            return Json(new { total = source.Count(), rows = result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult OrderContent(int id = 0)
        {
            var o = context.Order.FirstOrDefault(s => s.Id == id);
            if (o == null)
                return Json("无内容", JsonRequestBehavior.AllowGet);
            return Json(o.Contents, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region  /*(-_-)*/友情链接/*(-_-)*/

        public ActionResult Links()
        {
            return View();
        }

        public JsonResult GetLinks(int page, int rows, string keyword, DateTime? datestart, DateTime? dateend)
        {
            IQueryable<Link> source = context.Link;
            if (!string.IsNullOrEmpty(keyword))
            {
                source = source.Where(c => c.Name.Contains(keyword));
            }
            if (datestart.HasValue)
                source = source.Where(s => s.CreationDate >= datestart.Value);
            if (dateend.HasValue)
                source = source.Where(s => s.CreationDate <= dateend.Value.AddDays(1));
            var result = source.OrderByDescending(c => c.Id).Skip(rows * (page - 1)).Take(rows);
            return Json(new { total = source.Count(), rows = result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetLink(int Id)
        {
            return Json(context.Link.FirstOrDefault(c => c.Id == Id), JsonRequestBehavior.AllowGet);
        }


        [HttpPost, ValidateInput(false)]
        public ActionResult Link(int Id = 0)
        {
            Link c;
            if (Id == 0)
            {
                c = new Models.Link();
                context.Link.Add(c);
            }
            else
            {
                c = context.Link.First(cc => cc.Id == Id);
            }
            UpdateModel(c);
            c.CreationDate = DateTime.Now;
            context.SaveChanges();
            var result = new { result = "提交成功" };
            return Json(result, "text/html");
        }

        [HttpPost]
        public JsonResult DeleteLink(int id)
        {
            context.Link.Remove(context.Link.FirstOrDefault(c => c.Id == id));
            context.SaveChanges();
            return Json(new { result = true, msg = "删除友情链接成功" }, "text/html");
        }
        #endregion

        #region  /*(-_-)*/上传/*(-_-)*/

        static string[] AllowExs = new string[] { ".jpg", ".gif", ".png" };
        [HttpPost]
        public ContentResult Upload(string id)
        {
            if (Request.Files == null || Request.Files.Count == 0) return Content("ERROR");
            var file = Request.Files[0];
            if (file.ContentLength == 0) return Content("ERROR");
            var ex = System.IO.Path.GetExtension(file.FileName).ToLower();
            if (!AllowExs.Contains(ex)) return Content("ERROR");

            string path = Request.PhysicalApplicationPath + "Upload\\" + id + "\\";
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random(DateTime.Now.Millisecond).Next(9999) + ex;

            try
            {
                file.SaveAs(path + filename);
                return Content("/Upload/" + id + "/" + filename, "text/html");
            }
            catch
            {
                return Content("ERROR");
            }
        }
        #endregion
    }

    public class Category
    {
        public int id { get; set; }
        public int? pid { get; set; }
        public string name { get; set; }
        public string nameEn { get; set; }
        public string description { get; set; }
        public string descriptionEn { get; set; }
        public IEnumerable<Category> children { get; set; }
    }
}
